<?php
    /**
	 * Created by Ailcc.com
     * 2021-11-14 12:00:00 沛霖主页
     * 
	 */
declare (strict_types = 1);

namespace app\index\controller;

use app\common\model\UrlModel;
use app\common\model\NewsModel;
use app\common\model\SettingModel;
use app\common\model\DingdingModel;     //钉钉消息通知
use app\common\model\MessagesModel;
use app\common\model\NewsCategoryModel;
use think\facade\Cookie;
use think\facade\Lang;
use think\facade\View;

class News extends Common
{
	protected function initialize()
	{
		parent::initialize(); // TODO: Change the autogenerated stub
	}

	public function index(){
        $cid = input('cid',1);
        $map = [];
        if (!is_numeric($cid)) {     //判断ID是否为字符或数字
            $id_name = $cid ;      //如为字符则查询查询字符所属文章ID
            if ($id_name) {       //判断个性域名
                $item = NewsCategoryModel::where("name",$id_name)->find();
                if ($item['id']) {
                    $cid = $item['id'] ;
                }
            }
        }
        if(!empty($cid)){
	        $categoryInfo = NewsCategoryModel::where('id',$cid)->find();
	        if($categoryInfo->pid===0){
	        	$categorySubIdArr = NewsCategoryModel::where('pid',$categoryInfo->id)->column('id');
	        	array_push($categorySubIdArr,$cid);
		        $map[] = ['category_id','in',$categorySubIdArr];
	        }else{
		        $map[] = ['category_id','=',$cid];
	        }
        }
	    $map[] = ['status','=',1];
        $list = NewsModel::pageList($map,12);
        // 获取分页显示
        $page = $list->render();

	    $currentCategory = NewsCategoryModel::where('id',$cid)->find();
	    View::assign('cid',$cid);
	    $head_id = $cid;
	    View::assign('head_id',$head_id);

	    if(!empty($currentCategory->pid)){
		    $categoryPid = $currentCategory->pid;
	    }else{
		    $categoryPid = $currentCategory->id;

	    }
	    $currentCategoryList = NewsCategoryModel::where('pid',$categoryPid)->whereOr('id',$categoryPid)->order('sort','ASC')->select();
        $listnames = NewsCategoryModel::where('pid',0)->where('id',$categoryPid)->order('sort','ASC')->value('title');
        $listimage = NewsCategoryModel::where('pid',$categoryPid)->whereOr('id',$categoryPid)->order('sort','ASC')->value('ename');
        $list_name_fl = NewsCategoryModel::where('pid',$categoryPid)->whereOr('id',$categoryPid)->order('sort','ASC')->value('title');
        
	    View::assign('currentCategoryList',$currentCategoryList);
	    View::assign('listnames',$listnames);
	    View::assign('listimage',$listimage);
	    View::assign('list_name_fl',$list_name_fl);

        return view('index',['list'=>$list,'page'=>$page]);
    }

    public function show(){
        $id = input('id');
        $act = input('act','');
		if (!is_numeric($id)) {     //判断ID是否为字符或数字
            $id_domain = $id ;      //如为字符则查询查询字符所属文章ID
            if ($id_domain) {       //判断个性域名
                $item = NewsModel::where("id_domain",$id_domain)->find();
                if ($item['id']) {
                    $id = $item['id'] ;
                }
            }
        }
        
	    $head_id = $id;
	    View::assign('head_id',$head_id);
        $info = NewsModel::info($id);
		if(empty($info)){
// 			echo '暂无数据';
            abort(32571, '页面异常');
			exit;
		}
        $news_cookie = 'news_cookie_'.$id;
        $cookie = Cookie::get($news_cookie);
        if(!$cookie){
            NewsModel::where('id', $id)->inc('clicks', 1)->update();
            cookie($news_cookie,$id, 18000);
        }

        $prev = NewsModel::prev($info,1);
        $next = NewsModel::next($info,1);

	    if(!empty($info)){
		    $currentCategory = NewsCategoryModel::find($info->category_id);
			$info->currentName = $currentCategory->title;
			if($currentCategory->name == ''){       //判断文章分类是否有个性地址
			    $info->CidUrl = UrlModel::getNewsUrl($currentCategory->category_id);
			}else{
			    $info->CidUrl = UrlModel::getNewsUrl($currentCategory->name);
			}
			if($info->id_domain == ''){     //判断文章是否有个性地址
			    $info->IdUrl = UrlModel::getShowUrl($info->id);
			}else{
			    $info->IdUrl = UrlModel::getShowUrl($info->id_domain);
			}
			//生成文章目录锚点
            $config = SettingModel::where('group',$this->lang)->column('value','name');
			if($config['use_post_menu'] == 'on'){
    			$content = $info['content'];
    			if($content){
        			if (preg_match_all("/<h[12345]>(.*?)<\/h[12345]>/im", $content, $ms)) {
                        foreach ($ms[1] as $i => $title) {
                            $start = stripos($content, $ms[0][$i]);
                            $end = strlen($ms[0][$i]);
                            $level = substr($ms[0][$i], 1, 2);
                            $content = substr_replace($content, "<$level id=\"pk-menu-${i}\">{$title}</{$level}>", $start, $end);
                        }
                        
                    }
                    $info->contents = $content;
    			}
			}else{
			    $info->contents = $info['content'];
			}
// 		    View::assign('currentCategoryName',$currentName);
// 		    View::assign('cid',$infoCid);
// 		    View::assign('newsid',$infoId);     //输出文章ID或个性地址
        
            View::assign('info',$info);
            View::assign('prev',$prev);
            View::assign('next',$next);

		    if(!empty($currentCategory->pid)){
		    	$categoryPid = $currentCategory->pid;
		    }else{
			    $categoryPid = $currentCategory->id;

		    } 
		    $currentCategoryList = NewsCategoryModel::where('pid',$categoryPid)->whereOr('id',$categoryPid)->order('sort','ASC')->select();
		    View::assign('currentCategoryList',$currentCategoryList);
	    }
        
        $list = MessagesModel::where('pcode',0)->where('pid',$id)->where('status','1')->order('create_time desc')->paginate(20);
		$count = $list->total();     //获取评论总数
        $commlist = $this->getCommlist();   //获取评论列表
        $page = $this->getCommlist();// 获取分页显示
        return view('show',['commlist'=>$commlist,'page'=>$page,'count'=>$count]);
    }
    
    public function getCommlist($pcode=''){ 
        $pid = input('id');   
		if (!is_numeric($pid)) {     //判断ID是否为字符或数字
            $id_domain = $pid ;      //如为字符则查询查询字符所属文章ID
            if ($id_domain) {       //判断个性域名
                $item = NewsModel::where("id_domain",$id_domain)->find();
                if ($item['id']) {
                    $pid = $item['id'] ;
                }
            }
        }
        $res = MessagesModel::where('pcode',$pcode)->where('pid',$pid)->where('status','1')->order('create_time desc')->paginate(10,false,['query' => request()->param(),'type' => 'page\Page','var_page'  => 'page']);
		foreach($res as $k => $v){
		    if(!$v['phone_s']){
		      $messCount = MessagesModel::where("nickname",$v['nickname'])->where('status','1')->count();  
		    }else{
		      $messCount = MessagesModel::where("phone_s",$v['phone_s'])->where('status','1')->count();  
		    }
		    if($messCount < 10){
		        $res[$k]['diamond'] = '评论先锋 LV.1';    
		    }else if($messCount < 20){
		        $res[$k]['diamond'] = '评论达人 LV.2';
		    }else if($messCount < 30){
		        $res[$k]['diamond'] = '评论精英 LV.3';
		    }else if($messCount < 50){
		        $res[$k]['diamond'] = '评论大师 LV.4';
		    }else if($messCount < 70){
		        $res[$k]['diamond'] = '评论王者 LV.5';
		    }
	        $res2 = MessagesModel::where("pcode",$v['id'])->where('status','1')->select();
		    $res[$k]['children'] = $res2;
		}
		return $res;
    }
    
    public function NewsAjax(){
        $id = input('um_id');
        $action = input('action');
		if (!is_numeric($id)) {     //判断ID是否为字符或数字
            $id_domain = $id ;      //如为字符则查询查询字符所属文章ID
            if ($id_domain) {       //判断个性域名
                $item = NewsModel::where('id_domain',$id_domain)->find();
                if ($item['id']) {
                    $id = $item['id'] ;
                }
            }
        }
        $nowTime = time();  //时间
        $Dingip = get_client_ip();  //获取IP
        $auth = new DingdingModel();
        if(!$id){
            return json(['code'=>1, 'msg'=>'文章ID不能为空']);
        }else {
            $StTitle = NewsModel::where('id',$id)->value( 'title' );
        }
        if($action == 'puock_like'){
            $puock_like = $action.'_'.$id;
            $cookie = Cookie::get($puock_like);     //读取本地cookie
            if($cookie){                            //判断cookie是否存在
                return json(['e'=>1, 't'=>'你已经点过赞了!']);
            }else{
                NewsModel::where('id', $id)->inc('like', 1)->update();      //点赞数加1
                cookie($puock_like,$id, 18000);         //本地写入cookie
                $data = NewsModel::where('id', $id)->value('like');
                $Dingmsg = '网友给您标题为['.$StTitle.']的文章点了1个赞了，点赞IP：'.$Dingip.''; //钉钉通知
                $str = $auth->dingding_up($Dingmsg);
                return json(['e'=>0, 't'=>'点赞成功!','d'=>$data]);
            }
        }else if($action == 'pk_poster'){
            
            $info = NewsModel::info($id);
            $html ='';
            $peilin_home = '/static/image/peilin_home.png';    //海报logo图
            if(empty($info)){
                echo('无效的文章ID:'.$id.'');
    			exit;
            }else{
                $str = mb_strimwidth($info['description'], 0, 80) . '...'; //限制文章描述长度为80字符
                echo '
        <div class="post-poster">
            <div class="post-poster-main" id="post-poster-main-'.$id.'">
                <div class="cover">
                    <img src="'.$info['thumb'].'" alt="">
                </div>
                <div class="content">
                    <p class="title mt20 fs16">'.$info['title'].'</p>
                    <p class="excerpt fs14 mt20 c-sub">'.$str.'</p>
                    <div class="info mt20">
                        <img class="qrcode" src="'.$info['news_image'].'" alt="'.$info['title'].'">
                        <img class="logo" src="'.$peilin_home.'" alt="logo">
                    </div>
                    <p class="tip c-sub fs12 mt20 p-flex-center"><i class="fa-solid fa-qrcode"></i>&nbsp;长按识别二维码查看文章内容</p>
                </div>
            </div>
        </div>
        <script>
            $(function () {
                html2canvas(document.querySelector("#post-poster-main-'.$id.'"), {
                    allowTaint: true,
                    useCORS: true
                }).then(canvas => {
                    const el = $("#post-poster-main-'.$id.'");
                    el.show();
                    el.html("<img class=\'result\' src=\'" + canvas.toDataURL("image/png") + "\' alt=\''.$info['title'].'\'>");
                }).catch(err => {
                    console.error(err)
                    window.Puock.toast("生成海报失败，请到Console查看错误信息", TYPE_DANGER);
                });
            })
        </script>';
            } 
        }else if($action == 'pk_ajax_dialog_post_share'){
            $info = NewsModel::info($id);
            echo'
    <!-- 分享至第三方 -->
    <div class="d-flex justify-content-center w-100">
        <div data-id="wb" class="share-to circle-button circle-sm circle-hb text-center bg-danger text-light"><i class="layui-icon layui-icon-login-weibo t-md"></i></div>
        <div data-id="wx" id="wx-share" data-bs-toggle="tooltip" data-bs-html="true" data-bs-title="<p class=\'text-center t-sm mb-1 mt-1\'>使用微信扫一扫</p>
            <img width=\'120\' height=\'120\' class=\'mb-1\' alt=\'微信二维码\' src=\''.$info['news_image'].'\'>" class="share-to circle-button circle-sm circle-hb text-center bg-success text-light"><i class="layui-icon layui-icon-login-wechat t-md"></i></div>
        <div data-id="qzone" class="share-to circle-button circle-sm circle-hb text-center bg-warning text-light"><i class="layui-icon layui-icon-login-qq t-md"></i></div>
        <div data-id="tw" class="share-to circle-button circle-sm circle-hb text-center bg-info text-light"><i class="layui-icon layui-icon-twitter-fill t-md"></i></div>
        <div data-id="fb" class="share-to circle-button circle-sm circle-hb text-center bg-primary text-light"><i class="layui-icon layui-icon-facebook t-md"></i></div>
    </div>';
        }
    }
    
	public function search(){
		$keyword = input('keyword');
		$map = [];
		if(!empty($keyword)){
			$map[] = ['title','like','%'.$keyword.'%'];
		}
		$map[] = ['lang','=',$this->lang];
		$map[] = ['status','=',1];
		$list = NewsModel::pageList($map,10);
		// 获取分页显示
		$page = $list->render();

		return view('',['list'=>$list,'page'=>$page]);
	}

}
